package com.bandaotixi.cashier.api.core.handler;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * mybatis-plus 字段自动填充
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 新增填充创建时间
     *
     * @param metaObject 元数据
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class);
        try {
            this.strictInsertFill(metaObject, "createBy", StpUtil::getLoginIdAsString, String.class);
        } catch (Exception e) {
            log.warn("获取当前登录用户失败，填充创建人失败");
        }
        this.updateFill(metaObject);
    }

    /**
     * 更新填充更新时间
     *
     * @param metaObject 元数据
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
        try {
            this.strictUpdateFill(metaObject, "updateBy", StpUtil::getLoginIdAsString, String.class);
        } catch (Exception e) {
            log.warn("获取当前登录用户失败，填充更新人失败");
        }
    }

}
